/*
 * 作者：lovefc
 * 博客：http://lovefc.cn
 * 扣扣：1102952084 
 */

var counts = 0; // 消息总数
var zhihu_count = 0; // 知乎消息
var gitee_count = 0; // 码云消息
var weibo_count = 0; // 微博消息
var v2ex_count  = 0; // v2ex消息
var bili_count  = 0; // B站消息
var hupu_count  = 0; // 虎扑消息
var hu60_count  = 0; // hu60消息
var kanxue_count= 0; // 看雪论坛消息
var tieba_count = 0; // 百度贴吧

var timestamp = (new Date()).getTime();

// 初始化列表
var jsonlist = {zhihu:'zhihu',bili:'bili',tieba:'tieba',v2ex:'v2ex',kanxue:'kanxue'};
chrome.storage.sync.set(jsonlist, function() {
    console.log('保存成功');
});

// 检查是不是json字符串
function isJSON(str) {
    if (typeof str == 'string') {
        try {
            var obj=JSON.parse(str);
            if(typeof obj == 'object' && obj ){
                return true;
            }else{
                return false;
            }

        } catch(e) {
            return false;
        }
    }
    return false;
}


// 获取消息总数
function getCounts(){
	return counts;
}
function getTiebaCount(){
	return tieba_count;
}
function getHupuCount(){
	return hupu_count;
}
function getKanxueCount(){
	return kanxue_count;
}
function getHu60Count(){
	return hu60_count;
}
function getZhihuCount(){
	return zhihu_count;
}
function getGiteeCount(){
	return gitee_count;
}
function getWeiboCount(){
	return weibo_count;
}
function getV2exCount(){
	return v2ex_count;
}
function getBiliCount(){
	return bili_count;
}
function setMsg(str){
	chrome.browserAction.setBadgeText({text: str});
	chrome.browserAction.setBadgeBackgroundColor({color:'#B22222'});	
}

// 消息总数
function setMsgCount() {
	counts = zhihu_count + gitee_count + weibo_count + v2ex_count + bili_count + hu60_count + kanxue_count + tieba_count;
	if(counts!=0){
		setMsg(counts.toPrecision());
	}else{
		setMsg('');
		chrome.browserAction.setIcon({path:"img/default.png"});
	}
};


// 贴吧消息获取
function getTiebaMsgCount() {
	var xhr = new XMLHttpRequest();
	xhr.open("GET", "https://tieba.baidu.com/index/tbwise/forum?shownew=1");
	xhr.onreadystatechange = function () {
		if (xhr.readyState == 4) {
			var data = xhr.responseText;
            var number = 0;
            var reg  = new RegExp('src=0">\((.+?)\)</a>', "ig");
            var res = reg.exec(data);
			var res2 = reg.exec(data);
	        if(res){
				res  = res[1];
				res2 = res2[1];
				var num  = parseInt(res.replace(/[^0-9]/ig,""));
				var num2 = parseInt(res2.replace(/[^0-9]/ig,""));
				number = num +num2;
                if(number && number!=0){
			        chrome.browserAction.setIcon({path:"img/tieba.png"});
			    }
			}
		    tieba_count = number;
		}
	}
	xhr.send();
};

// 获取虎扑消息
function getHupuMsgCount(){
	var xhr = new XMLHttpRequest();
	xhr.open("GET", "https://my.hupu.com/notifications/json");
	xhr.onreadystatechange = function () {
		if (xhr.readyState == 4) {
			var res = xhr.responseText;
			var number = 0;
            if(res){
                var data = JSON.parse(res);
				//{"msg":2,"remind":0,"notifications":2,"notificationsinfo":[]}
			   var number = parseInt(data['msg']);
			   if(number && number!=0){
			       chrome.browserAction.setIcon({path:"img/hupu.png"});
			   }
			}
			hupu_count = number;
		}
	}
	xhr.send();	
}

// 获取看雪论坛消息
function getKanxueMsgCount(){
	var xhr = new XMLHttpRequest();
	xhr.open("GET", "https://www.kanxue.com/pm-new.htm");
	xhr.onreadystatechange = function () {
		if (xhr.readyState == 4) {
			var data = xhr.responseText;
			var number = 0;
			if(isJSON(data)){
			   var json = JSON.parse(data);
			   var number = parseInt(json['message']);
			   if(number && number!=0){
			       chrome.browserAction.setIcon({path:"img/kanxue.png"});
			   }
			}
			kanxue_count = number;
		}
	}
	xhr.send();	
}

// 获取b站消息
function getBiliMsgCount(){
	var xhr = new XMLHttpRequest();
	xhr.open("GET", "https://api.vc.bilibili.com/session_svr/v1/session_svr/single_unread?unread_type=0&build=0&mobi_app=web");
	xhr.onreadystatechange = function () {
		if (xhr.readyState == 4) {
			var data = xhr.responseText;
			var number = 0;	
			if(isJSON(data)){
				var json = JSON.parse(data);

				if(json.code == 0){
			       var unfollow_unread = parseInt(json['data']['unfollow_unread']);
			       var follow_unread = parseInt(json['data']['follow_unread']);
			       number = unfollow_unread + follow_unread;
				}else{
					number = 0;
				}
            }
			if(number && number!=0){
			   chrome.browserAction.setIcon({path:"img/bili.png"});
			}
			bili_count = number;
		}
	}
	xhr.send();	
}


// 获取知乎消息
function getZhihuMsgCount() {
	var xhr = new XMLHttpRequest();
	xhr.open("GET", "https://www.zhihu.com/api/v4/me");
	xhr.onreadystatechange = function () {
		if (xhr.readyState == 4) {
			var data = xhr.responseText;
			var number = 0;
			if(isJSON(data)){
			    var json = JSON.parse(data);
			    var messages_count = json['messages_count'];
			    var default_notifications_count = json['default_notifications_count'];
			    var vote_thank_notifications_count = json['vote_thank_notifications_count'];
			    var follow_notifications_count = json['follow_notifications_count'];
				var number = messages_count + default_notifications_count + vote_thank_notifications_count + follow_notifications_count;
            }
			if(number && number!=0){
			   chrome.browserAction.setIcon({path:"img/zhihu.png"});
			}
			zhihu_count = number;
		}
	}
	xhr.send();
};

// 获取码云消息
function getGiteeMsgCount() {
	var xhr = new XMLHttpRequest();
	xhr.open("GET", "https://gitee.com/notifications/unread_count");
	xhr.onreadystatechange = function () {
		if (xhr.readyState == 4) {
			var data = xhr.responseText;
			var number = 0;
			if(data){
			    var json = JSON.parse(data);
			    var count = json['total'];
			    number = parseInt(count);
                if(number && number!=0){
			       chrome.browserAction.setIcon({path:"img/gitee.png"});
			    }
		    }
		    gitee_count = number;
	     }
	}
	xhr.send();
};

// 获取微博消息
/*
function getWeiboMsgCount() {
	var xhr = new XMLHttpRequest();
	var timestamp = (new Date()).getTime();
	xhr.open("GET", "https://m.weibo.cn/api/remind/unread?t="+timestamp);
	xhr.onreadystatechange = function () {
		if (xhr.readyState == 4) {
			var data = xhr.responseText;
			var json = JSON.parse(data);
			var number = 0;
			if(json){
			   var msgs = json['data']['unreadmsg'];
			   for (i in msgs){
                   number += parseInt(msgs[i]);
               }
			}
            if(number && number!=0){
			   chrome.browserAction.setIcon({path:"img/weibo.png"});
			}
			weibo_count = number;
		}
	}
	xhr.send();
};
*/

// 新的微博消息获取
function getWeiboMsgCount() {
	var xhr = new XMLHttpRequest();
	xhr.open("GET", "https://weibo.cn");
	xhr.onreadystatechange = function () {
		if (xhr.readyState == 4) {
			var data = xhr.responseText;
            var number = 0;
            var reg = new RegExp('<span class="tmn">([0-9]+?)</span>', "ig");
            var result = reg.exec(data);
	        if(result){
				number = parseInt(result[1]);
                if(number && number!=0){
			        chrome.browserAction.setIcon({path:"img/weibo.png"});
			    }
			}
			weibo_count = number;
		}
	}
	xhr.send();
};

// 获取v2ex消息
function getV2exMsgCount() {
	v2ex_count = 0;
	var xhr = new XMLHttpRequest();
	xhr.open("GET", "https://www.v2ex.com");
	xhr.onreadystatechange = function () {
		if (xhr.readyState == 4) {
			var data = xhr.responseText;
			var reg = new RegExp('<a href="/notifications">([0-9]+?) 条未读提醒</a>', "ig");  
            var result = reg.exec(data);
            if(result){			
			    var number = parseInt(result[1]);
                if(number && number!=0){
			        chrome.browserAction.setIcon({path:"img/v2ex.png"});
			    }
				v2ex_count = number;
			}
		}
	}
	xhr.send();
};

// 获取HU60消息
function getHu60MsgCount() {
	hu60_count = 0;
	var xhr = new XMLHttpRequest();
	xhr.open("GET", "https://hu60.cn/q.php/index.index.html");
	xhr.onreadystatechange = function () {
		if (xhr.readyState == 4) {
			var data = xhr.responseText;
			var number = 0;
            var reg = new RegExp('<a href="msg.index.inbox.no.html">(.+?)</a>', "ig");
			var result = reg.exec(data);
			if(result){
				datas = result[1];
				number = parseInt(datas.replace(/[^0-9]/ig,""));
				if(number && number!=0){
			        chrome.browserAction.setIcon({path:"img/hu60.png"});
			    }
			}
			hu60_count = number;
		}
	}
	xhr.send();
};

// 运行
function run(jsons){
    if("gitee" in jsons){
       getGiteeMsgCount();
    }else{
	   gitee_count = 0;
	}
    if("hupu" in jsons){
       getHupuMsgCount();
    }else{
	   hupu_count = 0;
	}	
	if("zhihu" in jsons){
       getZhihuMsgCount();
	}else{
	   zhihu_count = 0;
	}
	/*
	if("weibo" in jsons){
       getWeiboMsgCount();
	}else{
	   weibo_count = 0;
	}
	*/
	if("v2ex" in jsons){
       getV2exMsgCount();
	}else{
	   v2ex_count = 0;
	}
	if("bili" in jsons){
       getBiliMsgCount();
	}else{
	   bili_count = 0;
	}
	if("hu60" in jsons){
       getHu60MsgCount();
	}else{
	   hu60_count = 0;
	}
    if("kanxue" in jsons){
	   getKanxueMsgCount();	
	}else{
	   kanxue_count = 0;	
	}
	if("tieba" in jsons){
	   getTiebaMsgCount();	
	}else{
	   tieba_count = 0;	
	}
    setMsgCount();	
}

// 初始化函数
function init(){
    chrome.storage.sync.get(null,function(jsons){ 
        run(jsons); 
    });	
}

// 定时抓取
setInterval(function(){
	init();
},6666);